<template>
  <div class="quick-sort-animation">
    <div
      v-for="(item, index) in array"
      :key="index"
      class="array-item"
      :style="{ height: item * 10 + 'px' }"
    ></div>
    <button @click="startSort">开始排序</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, inject } from 'vue';

export default defineComponent({
  name: 'QuickSortAnimation',
  setup() {
    // const array = ref([34, 7, 23, 32, 5, 62, 32, 12, 19]);
    const origins = inject<number[]>('origins');
    const array: number[] = ref(JSON.parse(JSON.stringify(origins)));
    const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

    const partition = async (arr: number[], low: number, high: number): Promise<number> => {
      const pivot = arr[high];
      let i = low - 1;
      for (let j = low; j < high; j++) {
        if (arr[j] < pivot) {
          i++;
          [arr[i], arr[j]] = [arr[j], arr[i]];
          await sleep(50); // 等待500ms以展示交换过程
        }
      }
      [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
      await sleep(50); // 等待500ms以展示交换过程
      return i + 1;
    };

    const quickSort = async (arr: number[], low: number, high: number): Promise<void> => {
      if (low < high) {
        const pi = await partition(arr, low, high);
        await quickSort(arr, low, pi - 1);
        await quickSort(arr, pi + 1, high);
      }
    };

    const startSort = async () => {
      await quickSort(array.value, 0, array.value.length - 1);
    };

    return {
      array,
      startSort,
    };
  },
});
</script>

<style scoped>
.quick-sort-animation {
  display: flex;
  align-items: flex-end;
  height: 300px;
  margin: 20px;
}

.array-item {
  width: 20px;
  background-color: #42b983;
  margin: 0 2px;
}
</style>
